package com.peng.rpc.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据类型创建创建单例对象（注意保证该类构造私有）
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/3/7 9:26
 */
public class SingletonFactory {
    private static final Map<Class, Object> objectMap = new HashMap<>();

    public static<T> T getSingletonInstance(Class<T> clazz) {
        if (!objectMap.containsKey(clazz)) {
            synchronized (objectMap) {
                if (!objectMap.containsKey(clazz)) {
                    try {
                        Constructor<T> constructor = clazz.getDeclaredConstructor();
                        constructor.setAccessible(true);
                        objectMap.put(clazz, constructor.newInstance());
                    } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return (T) objectMap.get(clazz);
    }

}
